package com.example.demo.config;

import java.util.HashMap;

import javax.sql.DataSource;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.example.demo.route.MyRoutingDataSource;
import com.google.common.collect.Maps;

/**
 * @author 作者 zj:
 * @version 创建时间：2019年2月1日 上午11:31:09
 * 多数据源配置
 */

@Configuration
public class DataSourceConfig {

	
	@Bean
	@ConfigurationProperties("spring.datasource.master")
	public DataSource masterDataSource(){
		return DataSourceBuilder.create().build();
	}
	
	@Bean
	@ConfigurationProperties("spring.datasource.slave1")
	public DataSource slave1DataSource(){
		return DataSourceBuilder.create().build();
	}
	
	@Bean
	@ConfigurationProperties("spring.datasource.slave2")
	public DataSource slave2DataSource(){
		return DataSourceBuilder.create().build();
	}
	
	@Bean
	public DataSource myRoutingDataSource(){
		HashMap<Object, Object> targetDataSources = Maps.newHashMap();
		targetDataSources.put(DBTypeEnum.MASTER, masterDataSource());
		targetDataSources.put(DBTypeEnum.SLAVE1, slave1DataSource());
		targetDataSources.put(DBTypeEnum.SLAVE2, slave2DataSource());
		
		MyRoutingDataSource myRoutingDataSource = new MyRoutingDataSource();
		myRoutingDataSource.setDefaultTargetDataSource(masterDataSource());
		myRoutingDataSource.setTargetDataSources(targetDataSources);
		return myRoutingDataSource;
	}
}
